% allows to rapidly do the manual selection for driftCorrectedKymograph
% without having to load the whole movie; the selections are saved which
% can then be made into kymographs with batchKymograph.m

%% set some parameter values:
deinterleave = 0;
movframes = [30,130];
frameSmoothing = 80;
drawingfig = figure;

%% select appropriate files
fn = uigetfile('*.tif','select rbc velocity movies','Multiselect','on');

if ~iscell(fn)
    temp = fn;
    fn = cell(1); fn{1} = temp;
end

%%
if deinterleave
    temp = movframes(2)-movframes(1);
    movframes = movframes(1):2:(movframes(1)+2*temp);
else
    movframes = movframes(1):movframes(2);
end

nummovies = length(fn);
movclips = cell(size(fn));
progbar = waitbar(0,'loading frames');
for n = 1:length(fn)
    movclips{n} = loadTiffStack2_SI(fn{n},movframes);
    waitbar(n/length(fn),progbar,'loading frames');
end
close(progbar);
%% do some basic processing on the movies:
avVessel = cell(size(movclips));    %will contain a smoothed image of the vessel
for n = 1:length(movclips)
    for n2 = 1:length(movframes)
        temp = medfilt2(movclips{n}(:,:,n2),[5,5]);
        movclips{n}(:,:,n2) = imgaussfilt(temp,5);
    end
    movclips{n} = movclips{n}-prctile(movclips{n}(:),10);
    avVessel{n} = mean(movclips{n},3);
end


%% manually draw line for kymograph generation:
lims = cell(size(avVessel));
ep = cell(size(avVessel));
for n = 1:length(avVessel)
    figure(drawingfig)
    while true
        imagesc(avVessel{n});
        if 0
            disp('select ROI')
            croprect = drawrectangle(gca);
            temp = round(croprect.Position(1)):(round(croprect.Position(1)+croprect.Position(3)));
            if temp(1) < 1
                temp(1) = 1;
            end
            if temp(end) > size(avVessel{n},2)
                temp = temp(temp<size(avVessel{n},2));
            end
        else
            temp = 10:(size(avVessel{n},2)-10);     %skip the ROI selection - that's not helping right now
        end
        lims{n} = temp;
        %lims{n} = round(croprect.Position(1)):(round(croprect.Position(1)+croprect.Position(3)));
        avVessel{n} = avVessel{n}(:,lims{n},:);
        imagesc(avVessel{n});
        disp('select line for kymograph generation');
        kymline = drawline(gca);
        sent = input('keep line[1], reselct[0], skip[2]: ');
        if sent == 1
            break;
        elseif sent == 2
            clear kymline
            kymline.Position = nan;
            break;
        end
    end
    ep{n} = round(kymline.Position);
end

% save this data for use later if you want:
for n = 1:length(fn)
    if isnan(ep{n})
        continue;
    end
    savename = strrep(fn{n},'.tif','_kymograph.mat');
    lineEndpoints = ep{n};
    cropping = lims{n};
    movname = fn{n};
    save(savename,'lineEndpoints','cropping','movname');
end
